#include <my_global.h>
#include <mysql.h>

#define HOST "localhost"
#define USER "sathvik"
#define PASSWD "keepworking"
#define DATABASE "testdb"

int main(int argc, char **argv)
{

  MYSQL *conn;
  MYSQL_RES *result_tables_set, *result_set;
  MYSQL_ROW row, table_names_row;
  char query_string[180], search_str[40], attribute[30]; 
  int i, num_fields;

  conn = mysql_init(NULL);

  if (conn == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

  if (mysql_real_connect(conn, HOST, USER, PASSWD, DATABASE, 0, "/var/lib/mysql/mysql.sock", 0) == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

  /* Input the search string & run a query on all the tables for the given column attribute */
  printf("\nEnter the string to be searched for in all the tables : \n");
  scanf("%s", search_str);
  printf("\nEnter the column name which is common to all the tables (say name, property etc) : \n");
  scanf("%s", attribute);

  /*Get a list of all the tables*/
  mysql_query(conn, "SHOW TABLES");
  result_tables_set = mysql_store_result(conn);

  while ((table_names_row = mysql_fetch_row(result_tables_set))) {
      /* For each table, pass a query if there are rows matching the given string for the given attribute */
      sprintf(query_string ,"SELECT * FROM %s where %s = \"%s\"", table_names_row[0], attribute, search_str); 
      mysql_query(conn, query_string);
      result_set = mysql_store_result(conn);
      num_fields = mysql_num_fields(result_set);

      printf("For Table: %s matching rows are \n", table_names_row[0]);
      while ((row = mysql_fetch_row(result_set))) {
          for(i = 0; i < num_fields; i++) {
              printf("%s   ", row[i] ? row[i] : "NULL");
          }
          printf("\n");
      }  
      printf("\n");
      mysql_free_result(result_set);
  }

  mysql_free_result(result_tables_set);
  mysql_close(conn);

  return 0;
}

